<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>拖拽</title>
    <style>
        #box1 {
            width: 200px;
            height: 200px;
            background-color: red;
            position: absolute;
        }
    </style>

    <script>

        window.onload = function () {

            /* 拖拽box1的元素
            *        -拖拽流程（一共三个事件）
            *               1-当鼠标在被拖拽元素上按下时，开始拖拽 onmousedown
            *               2-当鼠标移动时被拖拽元素跟随鼠标移动 onmousemove
            *               3-当鼠标松开时，被拖拽元素固定在当前位置 onmouseup
            */


            var box1 = document.getElementById("box1");

            box1.onmousedown = function (event) {
                event = event || window.event;

                //div的偏移量
                var ol = event.clientX - box1.offsetLeft;
                var ot = event.clientY - box1.offsetTop;

                document.onmousemove = function (event) {

                    event = event || window.event;

                    var left = event.clientX - ol;
                    var top = event.clientY - ot;

                    box1.style.left = left + "px";
                    box1.style.top = top + "px";
                }

                document.onmouseup = function () {
                    document.onmousemove = null;
                    document.onmouseup= null;
                    // alert("hhhh");
                }

                return false;
            }
       }
    </script>
</head>

<body>
    <div id="box1"></div>
</body>

</html>